<template>
  <view class="bg-[var(--page-bg-color)] min-h-[100vh]" :style="themeColor()">
    <view class="w-full bg-[var(--page-bg-color)]">
      <view class="pb-[210rpx] relative" :style="headerStyle">
        <!-- #ifdef MP-WEIXIN || APP-PLUS -->
        <top-tabbar
          :data="param"
          :scrollBool="topTabarObj.getScrollBool()"
          class="top-header"
        />
        <!-- #endif -->
        <view
          class="text-[70rpx] leading-[90rpx] text-[#fff] pl-[60rpx] font-500 pt-[77rpx] price-font h-[88rpx]"
        >
          <!-- {{ info?.available_points || 0 }} -->
        </view>
        <view class="flex items-center pl-[60rpx] h-[50rpx]">
          <!-- <image class="h-[36rpx] w-[36rpx] -mb-[4rpx]" :src="img('static/resource/images/member/point/icon.png')" mode="heightFix" />
                    <view class="text-[26rpx] leading-[36rpx] text-[#fff] ml-[10rpx]">我的积分</view> -->
        </view>
        <view
          v-if="btnShow"
          class="side-tab"
          :style="{ top: topStyle }"
          @click="redirect({ url: '/app/pages/member/available_detail' })"
        >
          <text class="nc-iconfont nc-icon-jifenduihuanV6xx1 icon"></text>
          <text class="desc">积分明细</text>
        </view>
      </view>
      <view class="sidebar-margin flex flex-col mt-[-178rpx] relative">
        <view
          class="w-[322rpx] h-[80rpx] text-[28rpx] text-[#333] font-500 box-border pl-[30rpx] pt-[var(--pad-top-m)] rounded-tl-[var(--rounded-big)] overflow-hidden mb-[-2rpx]"
          :style="{
            backgroundImage:
              'url(' + img('static/resource/images/member/point/top_bg.png') + ') ',
            backgroundSize: '100% 100%',
            backgroundRepeat: 'no-repeat',
          }"
        >
          <text class="leading-[42rpx]">可用积分</text>
        </view>
        <view
          class="flex flex-col items-start px-[30rpx] rounded-[var(--rounded-big)] !rounded-tl-none bg-[#fff] h-[223rpx] box-border"
        >
          <view class="text-[#333] text-[60rpx] py-[30rpx] price-font">{{
            info?.available_points || 0
          }}</view>
          <view class="text-[26rpx] py-[20rpx] text-[#999]"
            >积分来源：推广奖励、团队绩效奖励、绿色积分等可获得可用积分</view
          >
        </view>
      </view>
    </view>

    <view class="mt-[var(--top-m)] sidebar-margin card-template">
      <view class="type-content">
        <view
          class="type-item"
          :class="{ checked: handleType === 1 }"
          @click="changeType(1)"
          >转换兑换券</view
        >
        <view
          class="type-item"
          :class="{ checked: handleType === 2 }"
          @click="changeType(2)"
          >转账</view
        >
      </view>
    </view>
    <template v-if="handleType === 1">
      <view class="mt-[var(--top-m)] sidebar-margin card-template">
        <view class="title">兑换券</view>
        <view class="input-box">
          <input
            v-model.trim="exchange_quantity"
            type="number"
            placeholder="请输入可用积分"
            maxlength="10"
          />
          <view class="btn-right" @click="exchange">全部兑换</view>
        </view>
        <view class="title">兑换说明</view>
        <view class="text-[#999] text-[26rpx] leading-[54rpx] price-font"
          >1.最小可用积分为10积分</view
        >
        <view class="text-[#999] text-[26rpx] leading-[54rpx] price-font"
          >2.最大可用积分为100000积分</view
        >
        <view class="text-[#999] text-[26rpx] leading-[54rpx] price-font"
          >3.兑换手续费{{ exchangeTransRate }}%</view
        >
        <view
          v-if="digitalAssetSwitch"
          class="text-[#999] text-[26rpx] leading-[54rpx] price-font"
          >4.扣除手续费后，会有30%的可用积分转换为星星豆，转换比例：{{
            digitalAssetRate
          }}:1。</view
        >
      </view>
      <view class="mt-[var(--top-m)] sidebar-margin bottom-btn" @click="submit"
        >确认兑换</view
      >
    </template>
    <template v-if="handleType === 2">
      <view class="mt-[var(--top-m)] sidebar-margin card-template">
        <view class="title">账号</view>
        <view class="input-box">
          <input
            v-model.trim="transform.username"
            placeholder="请输入对方账号"
            maxlength="20"
          />
        </view>
        <view class="title mt-[20px]">转账积分</view>
        <view class="input-box">
          <input
            v-model.trim="transform.available_points"
            type="number"
            placeholder="请输入转账积分"
            maxlength="10"
          />
          <view class="btn-right" @click="exchangeTrans">全部</view>
        </view>
        <view class="title">转账说明</view>
        <view class="text-[#999] text-[26rpx] leading-[54rpx] price-font"
          >1.转账手续费{{ transRate }}%</view
        >
      </view>
      <view class="mt-[var(--top-m)] sidebar-margin bottom-btn" @click="submitTrans"
        >确认转账</view
      >
    </template>

    <!-- 支付密码组件 -->
    <pay-local ref="payLocalRef" @success="onPayPasswordSuccess" />
  </view>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from "vue";
import useMemberStore from "@/stores/member";
import useSystemStore from "@/stores/system";
import { redirect, img, pxToRpx } from "@/utils/common";
import { postExchangeGoldCoupons, getTransRate, postTransRate } from "@/app/api/member";
import { topTabar } from "@/utils/topTabbar";
import PayLocal from "@/components/pay-local/pay-local.vue";
const memberStore = useMemberStore();
const systemStore: any = useSystemStore();

/********* 自定义头部 - start ***********/
const topTabarObj = topTabar();
let param = topTabarObj.setTopTabbarParam({ title: "可用积分" });
/********* 自定义头部 - end ***********/

// 获取系统状态栏的高度
let menuButtonInfo: any = {};
// 如果是小程序，获取右上角胶囊的尺寸信息，避免导航栏右侧内容与胶囊重叠(支付宝小程序非本API，尚未兼容)
// #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO || MP-QQ
menuButtonInfo = uni.getMenuButtonBoundingClientRect();
// #endif
const headerStyle = computed(() => {
  return {
    backgroundImage:
      "url(" + img("static/resource/images/member/point/point_bg.png") + ") ",
    backgroundSize: "cover",
    backgroundRepeat: "no-repeat",
    backgroundPosition: "bottom",
    // paddingTop:Object.keys(menuButtonInfo).length?(Number(menuButtonInfo.height) * 2 + menuButtonInfo.top * 2 + 77)+'rpx':'77rpx',
  };
});
const topStyle = computed(() => {
  let top = "";
  // #ifdef MP
  top = Object.keys(menuButtonInfo).length
    ? pxToRpx(Number(menuButtonInfo.height)) + pxToRpx(menuButtonInfo.top) + 50 + "rpx;"
    : "50rpx";
  // #endif
  // #ifdef APP-PLUS
  top = systemStore.statusBarHeight + 50 + "px";
  // #endif
  return top;
});

//个人信息
const info = computed(() => {
  return memberStore.info;
});

const btnShow = computed(() => {
  return memberStore.buttonAuth.available_point || false;
});
const handleType = ref(1);
const exchange_quantity = ref<number>(); // 兑换券
const exchangeTransRate = ref<number>(0); // 兑换手续费
const digitalAssetSwitch = ref<number>(0); // 星星豆开关
const digitalAssetRate = ref<number>(0); // 星星豆比例
const transRate = ref<number>(0); // 转账手续费
const transform = ref<any>({
  username: "",
  available_points: "",
});

// 支付密码组件引用
const payLocalRef = ref();

onMounted(() => {
  getTransRate().then((res: any) => {
    exchangeTransRate.value = res.data.gold_coupons || 0;
    transRate.value = res.data.rate || 0;
    digitalAssetSwitch.value = res.data.digital_asset_switch || 0;
    digitalAssetRate.value = res.data.digital_asset_rate || 0;
  });
});

// 选择操作类型
const changeType = (type: number) => {
  handleType.value = type;
};

// 全部兑换
const exchange = () => {
  let val = info.value?.available_points || 0;
  if (val >= 100000) {
    exchange_quantity.value = 100000;
  } else {
    exchange_quantity.value = val;
  }
};

// 全部转账
const exchangeTrans = () => {
  let val = info.value?.available_points || 0;
  transform.value.available_points = val;
};

// 提交兑换
const submit = () => {
  if (!info.value.pay_password) {
    uni.showModal({
      title: "提示",
      content: "请先设置支付密码",
      confirmText: "去设置",
      showCancel: false,
      success: (res) => {
        if (res.confirm) {
          redirect({
            url: "/app/pages/paymentSetting/index",
          });
        }
      },
    });
    return;
  }
  if (!exchange_quantity.value) {
    uni.showToast({
      title: "请输入可用积分",
      icon: "none",
    });
    return;
  }
  if (exchange_quantity.value < 10) {
    uni.showToast({
      title: "最小可用积分为10积分",
      icon: "none",
    });
    return;
  }
  if (exchange_quantity.value > 100000) {
    uni.showToast({
      title: "最大可用积分为100000积分",
      icon: "none",
    });
    return;
  }
  if (exchange_quantity.value > parseFloat(info.value?.available_points)) {
    uni.showToast({
      title: "可用积分不足",
      icon: "none",
    });
    return;
  }

  // 弹出支付密码输入框
  payLocalRef.value?.open();
};

// 提交转账
const submitTrans = () => {
  if (!info.value.pay_password) {
    uni.showModal({
      title: "提示",
      content: "请先设置支付密码",
      confirmText: "去设置",
      showCancel: false,
      success: (res) => {
        if (res.confirm) {
          redirect({
            url: "/app/pages/paymentSetting/index",
          });
        }
      },
    });
    return;
  }
  if (!transform.value.username) {
    uni.showToast({
      title: "请输入用户账号",
      icon: "none",
    });
    return;
  }
  if (!transform.value.available_points) {
    uni.showToast({
      title: "请输入转账积分",
      icon: "none",
    });
    return;
  }
  if (transform.value.available_points > parseFloat(info.value?.available_points)) {
    uni.showToast({
      title: "可用积分不足",
      icon: "none",
    });
    return;
  }

  // 弹出支付密码输入框
  payLocalRef.value?.open();
};

// 支付密码验证成功后的回调
const onPayPasswordSuccess = () => {
  if (handleType.value === 1) {
    // 执行兑换操作
    executeExchange();
  } else if (handleType.value === 2) {
    // 执行转账操作
    executeTransfer();
  }
};

// 执行兑换操作
const executeExchange = () => {
  uni.showLoading({
    title: "兑换中...",
    mask: true,
  });
  postExchangeGoldCoupons({ exchange_quantity: exchange_quantity.value })
    .then((res) => {
      exchange_quantity.value = 0;
      setTimeout(() => {
        uni.showToast({
          title: "兑换成功",
          icon: "none",
        });
      }, 1000);
      memberStore.getMemberInfo();
    })
    .finally(() => {
      uni.hideLoading();
    });
};

// 执行转账操作
const executeTransfer = () => {
  uni.showLoading({
    title: "转账中...",
    mask: true,
  });
  postTransRate(transform.value)
    .then((res) => {
      transform.value.available_points = 0;
      transform.value.username = "";
      setTimeout(() => {
        uni.showToast({
          title: "转账成功",
          icon: "none",
        });
      }, 1000);
      memberStore.getMemberInfo();
    })
    .finally(() => {
      uni.hideLoading();
    });
};
</script>

<style lang="scss" scoped>
.bg-color {
  background-color: rgba(102, 102, 102, 0.4);
}
.bottom-btn {
  z-index: 999;
  text-align: center;
  color: #fff;
  padding: 20rpx;
  border-radius: 20rpx;
  background-color: #ff3e06;
  &:active {
    opacity: 0.8;
  }
}
</style>
